package com.jiguang.Electricvehicle;

import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.wanbang.hps.entrance.callback.HPSDecodeCallback;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zbar.ZBarView;

/**
 * @2Do:
 * @Author M2
 * @Version v ${VERSION}
 * @Date 2017/7/6 0006.
 */
public abstract class BaseQrActivity extends BaseSimpleActivity
        implements QRCodeView.Delegate {

    @BindView(R.id.zbarview)
    protected ZBarView mZBarView;

    @BindView(R.id.tv_operation)
    protected TextView tvOperation;


    @BindView(R.id.capture_scan_line)
    protected ImageView captureScanLine;

    @BindView(R.id.rl_capture_crop)
    protected RelativeLayout rlCaptureCrop;

    @BindView(R.id.ll_edt_code)
    protected LinearLayout llEdtCode;

    @BindView(R.id.chb_switch_scan)
    protected CheckBox chbSwitchScan;

    @BindView(R.id.chb_scan_light)
    protected CheckBox chbScanLight;

    @BindView(R.id.btn_submit)
    protected TextView btnSubmit;

    @BindView(R.id.edit_code)
    protected EditText editCode;

    @BindView(R.id.chb_scan_photo)
    protected CheckBox photoCheckbox;


    @BindView(R.id.view_top)
    protected View viewTop;

    @BindView(R.id.view_bottom)
    protected View viewBottom;

    @BindView(R.id.view_left)
    protected View viewLeft;


    @BindView(R.id.iv_delete_number)
    ImageView ivDeleteNumber;

    private static final String TOAST_HINT = "未获取到二维码图片";
    private static final String LOG_HINT = "未获取到二维码图片-------------";
    private static final String LOG_TAG = "msg-----";

    private static final float BEEP_VOLUME = 0.50f;
    /* 闪光时长 */
    private static final long VIBRATE_DURATION = 200L;
    private final MediaPlayer.OnCompletionListener beepListener = mBeepPlayer -> mBeepPlayer.seekTo(0);
    private MediaPlayer mediaPlayer;
    private boolean playBeep;
    private boolean vibrate;
    private Runnable runnable;
    protected boolean isPic;//相册识别，埋点用


    protected int getStatusBarAlpha() {
        return 144;
    }


    protected abstract View getCaptureScanLine();

    protected abstract ImageView getBarcodeView();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 初始化 CameraManager
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        if (getCaptureScanLine() != null) {
            scanLineStartAnimation();
        }
        if (mZBarView != null) {
            mZBarView.setDelegate(this);
            // 仅识别扫描框中的码
            mZBarView.getScanBoxView().setOnlyDecodeScanBoxArea(true);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //二维码扫码组件开始扫码
        if (mZBarView != null) {
            runnable = () -> {
                mZBarView.startSpot();
                //声音&振动处理-------start
                playBeep = true;
                AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
                if (audioService != null && audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
                    playBeep = false;
                }
                initBeepSound();
                vibrate = true;
                if (getBarcodeView() != null) {
                    getBarcodeView().setVisibility(View.GONE);
                }
                //声音&振动处理-------end
            };
            mZBarView.post(runnable);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        //暂停扫码
        if (mZBarView != null) {
            mZBarView.removeCallbacks(runnable);
            runnable = null;
            mZBarView.stopCamera();
            mZBarView.stopSpot();
        }
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        handleDecode(result, null);
    }

    @Override
    public void onCameraAmbientBrightnessChanged(boolean isDark) {

    }

    @Override
    public void onScanQRCodeOpenCameraError() {
        Toast.makeText(this, TOAST_HINT, Toast.LENGTH_SHORT).show();

    }

    /**
     * 处理扫码结果
     *
     * @param stubId  桩编号
     * @param barcode bitMap
     */
    protected void handleDecode(String stubId, Bitmap barcode) {
        playBeepSoundAndVibrate();

        if (TextUtils.isEmpty(stubId)) {
            handleErrorDecode();
            // 连续扫描，不发送此消息扫描一次结束后就不能再次扫描
            restartPreview();
        } else {
            //扫描成功传入设备编号到设备详情界面
            if (null != barcode && null != getBarcodeView()) {
                getBarcodeView().setVisibility(View.VISIBLE);
                getBarcodeView().setImageBitmap(barcode);
            }
            handleSuccessDecode(stubId);
        }
    }

    @Override
    protected void onDestroy() {

        // 销毁二维码扫描控件
        if (mZBarView != null) {
            mZBarView.onDestroy();
        }
        super.onDestroy();

    }

    protected void scanLineStartAnimation() {
        TranslateAnimation mAnimation = new TranslateAnimation(TranslateAnimation.ABSOLUTE, 0f,
                TranslateAnimation.ABSOLUTE, 0f, TranslateAnimation.RELATIVE_TO_PARENT, 0f,
                TranslateAnimation.RELATIVE_TO_PARENT, 0.86f);
        mAnimation.setDuration(2000);
        mAnimation.setRepeatCount(-1);
        mAnimation.setRepeatMode(Animation.REVERSE);
        mAnimation.setInterpolator(new LinearInterpolator());

        getCaptureScanLine().setAnimation(mAnimation);
    }

    protected void scanLineStopAnimation() {
        getCaptureScanLine().clearAnimation();
    }

    /**
     * 初始化声音
     */
    private void initBeepSound() {
        if (playBeep && mediaPlayer == null) {
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);

            try {
                AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
                mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
                file.close();
                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                mediaPlayer.prepare();
            } catch (Exception e) {
                mediaPlayer = null;
            }
        }
    }

    /**
     * 播放声音和振动
     */
    protected void playBeepSoundAndVibrate() {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            if (vibrator != null) {
                vibrator.vibrate(VIBRATE_DURATION);
            }
        }
    }


    /**
     * 开启闪光灯
     */
    protected void openLight() {
        if (mZBarView == null) {
            return;
        }
        mZBarView.openFlashlight();
    }

    /**
     * 关闭闪光灯
     */
    protected void closeLight() {
        if (mZBarView == null) {
            return;
        }
        mZBarView.closeFlashlight();
    }

    protected abstract void handleSuccessDecode(String stubId);

    protected abstract void handleErrorDecode();

    /**
     * 重启扫码
     */
    protected void restartPreview() {
        if (mZBarView == null) {
            return;
        }
        mZBarView.startSpot();
    }

    /**
     * 停止预览
     */
    protected void stopPreview() {
        if (mZBarView == null) {
            return;
        }
        mZBarView.stopSpot();
    }

    @OnCheckedChanged({R.id.chb_switch_scan, R.id.chb_scan_light, R.id.chb_scan_photo})
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.chb_scan_light:
                if (isChecked) {
                    chbScanLight.setText(getResources().getString(R.string.close_light));
                    openLight();
                } else {
                    chbScanLight.setText(getResources().getString(R.string.open_light));
                    closeLight();
                }
                break;
            case R.id.chb_switch_scan:
                Drawable drawable;
                if (isChecked) {//处于手动输入桩编号状态
                    setSwitchScanText(getString(R.string.switch_scan));
                    SystemUtil.showKeyboard(this);
                    editCode.setFocusable(true);
                    editCode.setFocusableInTouchMode(true);
                    editCode.requestFocus();
                    addEditListenner();
                    stopPreview();
                    drawable = mContext.getResources().getDrawable(R.drawable.switch_qr_scan);
                } else {
                    SystemUtil.closeKeybord(editCode, this);
                    setSwitchScanText(getSwitchScanText());
                    drawable = mContext.getResources().getDrawable(R.drawable.switch_qr_input);
                    dailyRestartPreview();
                }
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                chbSwitchScan.setCompoundDrawables(null, drawable, null, null);
                switchEditStatus(isChecked);
                break;
            case R.id.chb_scan_photo:
//                startLocationDecode(new HPSDecodeCallback<String>() {
//                    @Override
//                    public void onDecodeSuccess(HPSResponseBean<String> hpsResponseBean) {
//                        if (TextUtils.isEmpty(hpsResponseBean.getData())) {
//                            ToastUtil.toastShortMessage("无法识别图片中二维码");
//                        } else {
//                            handleSuccessDecode(hpsResponseBean.getData());
//                        }
//                    }
//
//                    @Override
//                    public void onDecodeFailed(HPSResponseBean hpsResponseBean) {
//                        ToastUtil.toastShortMessage("无法识别图片中二维码");
//                    }
//                });
                break;

            default:
                break;
        }
    }

    /**
     * 开始本地扫码识别
     * <p>
     * #@param decodeCallback 回调监听
     *
     * @return stubId
     */
    protected void startLocationDecode(HPSDecodeCallback<String> decodeCallback) {

    }

    private void addEditListenner() {
        editCode.setOnFocusChangeListener((v, hasFocus) -> {
            // 具备焦点并且文字不为空显示清除图标
            showClear(editCode.isFocused() && !TextUtils.isEmpty(editCode.getText().toString()));
        });

        editCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                showClear(editCode.isFocused() && !TextUtils.isEmpty(editCode.getText().toString()));
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void showClear(boolean visiable) {
        if (ivDeleteNumber != null) {
            ivDeleteNumber.setVisibility(visiable ? View.VISIBLE : View.GONE);
        }
    }

    public void setSwitchScanText(String text) {
        chbSwitchScan.setText(text);
    }

    public String getSwitchScanText() {
        return getString(R.string.manual_input_coupon);
    }

    private void dailyRestartPreview() {
        new Handler().postDelayed(() -> restartPreview(), 1000);
    }

    /**
     * 切换相机扫码或手动输入桩编号状态
     */
    protected void switchEditStatus(boolean isEdit) {
        if (isEdit) {//正在编辑状态
            captureScanLine.setVisibility(View.GONE);
            scanLineStopAnimation();
            rlCaptureCrop.setVisibility(View.GONE);
            viewBottom.setVisibility(View.GONE);
            viewTop.setVisibility(View.GONE);
            viewLeft.setVisibility(View.GONE);

            llEdtCode.setVisibility(View.VISIBLE);
            photoCheckbox.setVisibility(View.GONE);
        } else {
            SystemUtil.hideKeyboard(this);
            captureScanLine.setVisibility(View.GONE);
            scanLineStartAnimation();
            rlCaptureCrop.setVisibility(View.VISIBLE);
            viewBottom.setVisibility(View.VISIBLE);
            viewTop.setVisibility(View.VISIBLE);
            viewLeft.setVisibility(View.VISIBLE);
            llEdtCode.setVisibility(View.GONE);
            photoCheckbox.setVisibility(View.VISIBLE);
        }
    }
}
